package com.zhubayi.controller;

import com.github.pagehelper.PageInfo;
import com.zhubayi.constant.MyConstant;
import com.zhubayi.entity.History;
import com.zhubayi.entity.R;
import com.zhubayi.entity.User;
import com.zhubayi.entity.Video;
import com.zhubayi.entity.vo.HistoryVo;
import com.zhubayi.entity.vo.UserVo;
import com.zhubayi.entity.vo.VideoVo;
import com.zhubayi.exception.AccountExistException;
import com.zhubayi.exception.AccountNotFundException;
import com.zhubayi.exception.AccountWrongPasswordException;
import com.zhubayi.mapper.UserMapper;
import com.zhubayi.service.FavorService;
import com.zhubayi.service.HistoryService;
import com.zhubayi.service.UserService;
import com.zhubayi.service.VideoService;
import com.zhubayi.utils.FileUtils;
import com.zhubayi.utils.UserQueryConditionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author 祝八一
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    UserService userService;
    @Autowired
    VideoService videoService;
    @Autowired
    FavorService favorService;
    @Autowired
    HistoryService historyService;
    @RequestMapping("/logout")
    public String toLout(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user!=null){
            session.removeAttribute("user");
        }
        return "redirect:/toLogin";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }
    @PostMapping("login")
    public String login(HttpSession session, @RequestParam String username, @RequestParam String password, Model model, RedirectAttributes redirectAttributes){
        if (username!=null&&password!=null) {
            try {
                User user = userService.login(username, password);
                session.setAttribute("user",user);
            } catch (Exception e) {
                if (e instanceof AccountNotFundException) {
                    redirectAttributes.addFlashAttribute("msg", e.getMessage());
                } else if (e instanceof AccountWrongPasswordException) {
                    redirectAttributes.addFlashAttribute("msg", e.getMessage());
                } else {
                    redirectAttributes.addFlashAttribute("msg", "未知异常!");
                }
                //重定向
                redirectAttributes.addFlashAttribute("username", username);
                return "redirect:/toLogin";
            }


        }
        //添加到页面
        redirectAttributes.addFlashAttribute("username", username);
        return "redirect:/";
    }
    @RequestMapping("toReg")
    public String toReg(){
        return "register";
    }
    @RequestMapping(value = "register",method = RequestMethod.POST)
    public String Reg(@RequestParam String username,
                      @RequestParam String password,
                      @RequestParam String email,
                      Model model){
        User user = new User();
        user.setAccount(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setAvatar("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2853553659,1775735885&fm=26&gp=0.jpg");

        user.setRegTime(new Date());
        user.setScore(0);
        user.setStatus(true);
        user.setVideoNum(0);
        try {
            userService.register(user);
        } catch (AccountExistException e) {
            if (e instanceof AccountExistException){
             model.addAttribute("msg",e.getMessage());
             return "Reg";
            }
        }
        return "login";
    }
    @ResponseBody
    @GetMapping("exist")
    public Boolean isExist(@RequestParam String username){
        if (username!=null){
            if (userMapper.queryByName(username)==null){
                return false;
            }
            return true;
        }
        return true;
    }
    @GetMapping("ToSearch")
    public String toSearch(Model model){
        model.addAttribute("user",userMapper.queryAllUser());
        return "search";
    }
    @RequestMapping(value = "search",method = RequestMethod.POST)
    public String search(@RequestParam String username,
                         @RequestParam String email,
                         Model model){
        model.addAttribute("account",username);
        model.addAttribute("email",email);
        model.addAttribute("user",userMapper.queryByEmailOrByName(username,email));
        return "search";

    }
    @GetMapping("toHome")
    public String tohome(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return "redirect:/toLogin";
        }
        model.addAttribute("user",user);
        model.addAttribute("type","zhanghaoshezhi");
        return "home";
    }
    @PostMapping("updateAvatar")
    public String updateAvatar(Model model,HttpServletRequest request,@RequestParam MultipartFile avatar,String email) throws IOException {
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return "redirect:/toLogin";
        }
        if (avatar!=null){
            if (user.getAvatar()!=null){
                String[] str =user.getAvatar().split("/");
                //删除文件
                new File("D://test//uploadFile/avatar/"+str[str.length-1]).delete();
            }
            String url = FileUtils.uploadFile("avatar", avatar);
            userService.updateAvatar("http://127.0.0.1:8080/uploadFile/avatar/"+url,user.getId());
            user.setAvatar("http://127.0.0.1:8080/uploadFile/avatar/"+url);
        }
        user.setEmail(email);
        userService.update(user);
        model.addAttribute("user",user);
        model.addAttribute("type","zhanghaoshezhi");
        return "home";
    }

    /**
     * 我的视频
     * @param model
     * @return
     */
    @RequestMapping("toMyVideo")
    public String toMyVideo(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return "redirect:/toLogin";
        }
       List<VideoVo> videos= videoService.queryVoByUid(user.getId());
        System.out.println(videos);
        model.addAttribute("type","myVideo");
        model.addAttribute("videos",videos);
        return "myVideo";
    }
    /**
     * 我的收藏
     * @param model
     * @return
     */
    @RequestMapping("toMyFavor")
    public String toMyFavor(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return "redirect:/toLogin";
        }
       List<Video> videos= videoService.queryFavor(user.getId());
        System.out.println(videos);
        model.addAttribute("type","MyFavor");
        model.addAttribute("videos",videos);
        return "myFavor";
    }
    /**
     * 我的历史
     * @param model
     * @return
     */
    @RequestMapping("toMyHistory")
    public String toMyHistory(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return "redirect:/toLogin";
        }
        List<HistoryVo>  videos= historyService.queryByUid(user.getId());
        System.out.println(videos);
        model.addAttribute("type","MyHistory");
        model.addAttribute("videos",videos);
        return "history";
    }
    @ResponseBody
    @PostMapping("updatePassword")
    public R updatePassword(HttpServletRequest request,@RequestParam String oldpassword,@RequestParam String password ){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return new R(MyConstant.AUTHENTICATION);
        }
        return userService.updatePassword(user.getId(),oldpassword,password);

    }
    @ResponseBody
    @RequestMapping("great/{id}")
    public R great(@PathVariable("id") Integer id,HttpSession session){
        User user =(User) session.getAttribute("user");
        if (user==null){
            return new R(MyConstant.AUTHENTICATION);
        }
        Integer num=videoService.updateGreatNum(id,user.getId());
            return  new R(MyConstant.OK,num);


    }
}
